package chapter10.section6;

//程序10-10：账户对象输入和输出实例

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ObjectInOutDemo {
    // 将提供的集合中的账户对象保存到指定的文件中。
    public static void dataOut(String fn, List<Account> as) throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fn));
        for (Account a : as) {
            oos.writeObject(a);
        }
        oos.close();
    }

    // 从指定的文件中读取对象
    public static void dataIn(String fn) throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fn));
        while (true) {
            try {
                Account a = (Account) ois.readObject();
                System.out.println(a);
            } catch (EOFException e) {
                break;// 碰到文件尾，退出循环
            }
        }
        ois.close();
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        List<Account> as = new ArrayList<Account>();
        as.add(new Account("1600394098", "张伟", 2000));
        as.add(new Account("1600394099", "王国美", 3000));
        as.add(new Account("1600394118", "丁理惠", 2300));
        as.add(new Account("1600394120", "贺嘉怡", 12000));
        dataOut("account3.dat", as);
        dataIn("account3.dat");
    }
}